package com.example.projectmanagement.service;

import com.example.projectmanagement.model.Role;
import com.example.projectmanagement.model.Permission;
import com.example.projectmanagement.repository.RoleRepository;
import com.example.projectmanagement.repository.PermissionRepository;
import com.example.projectmanagement.repository.RolePermissionRepository;
import com.example.projectmanagement.repository.UserRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class RoleService {
    
    @Autowired
    private RoleRepository roleRepository;
    
    @Autowired
    private PermissionRepository permissionRepository;
    
    @Autowired
    private RolePermissionRepository rolePermissionRepository;
    
    @Autowired
    private UserRoleRepository userRoleRepository;
    
    /**
     * 获取所有角色
     */
    public List<Role> getAllRoles() {
        return roleRepository.findAll();
    }
    
    /**
     * 根据角色ID获取角色
     */
    public Role getRoleById(Long id) {
        return roleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("角色不存在"));
    }
    
    /**
     * 创建角色
     */
    public Role createRole(Role role) {
        if (roleRepository.findByRoleName(role.getRoleName()).isPresent()) {
            throw new RuntimeException("角色已存在");
        }
        return roleRepository.save(role);
    }
    
    /**
     * 更新角色
     */
    public Role updateRole(Long id, Role roleDetails) {
        Role role = getRoleById(id);
        role.setRoleName(roleDetails.getRoleName());
        role.setRoleDescription(roleDetails.getRoleDescription());
        return roleRepository.save(role);
    }
    
    /**
     * 删除角色
     */
    public void deleteRole(Long id) {
        Role role = getRoleById(id);
        
        // 检查角色是否关联了用户
        List<com.example.projectmanagement.model.UserRole> userRoles = userRoleRepository.findByRole_Id(id);
        if (!userRoles.isEmpty()) {
            throw new RuntimeException("该角色已关联用户，无法删除");
        }
        
        // 删除角色关联的权限
        rolePermissionRepository.deleteByRole_Id(id);
        roleRepository.delete(role);
    }
    
    /**
     * 获取所有权限
     */
    public List<Permission> getAllPermissions() {
        return permissionRepository.findAll();
    }
    
    /**
     * 根据角色ID获取权限
     */
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        return rolePermissionRepository.findPermissionsByRoleId(roleId);
    }
    
    /**
     * 为角色分配权限
     */
    public void assignPermissionsToRole(Long roleId, List<Long> permissionIds) {
        Role role = getRoleById(roleId);
        
        // 删除原有权限
        rolePermissionRepository.deleteByRole_Id(roleId);
        
        // 确保删除操作已经完成
        rolePermissionRepository.flush();
        
        // 去除重复的权限ID
        List<Long> distinctPermissionIds = permissionIds.stream().distinct().collect(Collectors.toList());
        
        // 添加新权限
        for (Long permissionId : distinctPermissionIds) {
            // 检查权限是否存在
            Optional<Permission> permissionOpt = permissionRepository.findById(permissionId);
            if (permissionOpt.isPresent()) {
                // 检查是否已经存在该角色权限关联
                com.example.projectmanagement.model.RolePermission rolePermission = 
                    new com.example.projectmanagement.model.RolePermission();
                rolePermission.setRole(role);
                rolePermission.setPermission(permissionOpt.get());
                rolePermissionRepository.save(rolePermission);
            }
        }
    }
    
    /**
     * 从角色中移除权限
     */
    public void removePermissionFromRole(Long roleId, Long permissionId) {
        rolePermissionRepository.deleteByRole_IdAndPermission_Id(roleId, permissionId);
    }
}